﻿using System;
using System.Collections.Generic;
using System.Text;
using Nexia.FluentHtmlElements.Utilities;

namespace Nexia.FluentHtmlElements.Elements
{
	public class ListBase<T> : ElementBase<T> where T : ListBase<T>
	{
		public ListBase(string name)
			: base(name)
		{			
		}

		private List<ListItem> _rawItems; 

		protected virtual List<ListItem> RawItems
		{
			get
			{
				if(_rawItems == null)
					_rawItems = new List<ListItem>();

				return _rawItems;
			}
			set
			{
				_rawItems = value;
			}
		}

		/// <summary>
		/// Determines how the HTML element is closed.
		/// </summary>
		protected internal override TagRenderMode TagRenderMode
		{
			get { return TagRenderMode.Normal; }
		}

		protected internal override void PreRender()
		{
			Builder.InnerHtml = RenderListItems();
			base.PreRender();
		}

		public override string ToString()
		{
			// Empty lists will return string.empty.
			return RawItems.Count < 1 ? String.Empty : base.ToString();
		}

		public T Items(IEnumerable<ListItem> items)
		{
			RawItems.AddRange(items);
			return (T) this;
		}

		public T AddListItem(ListItem item)
		{
			RawItems.Add(item);
			return (T)this;
		}

		private string RenderListItems()
		{
			var builder = new StringBuilder();

			foreach (var item in RawItems)
			{
				builder.Append(item.ToString());
			}

			return builder.ToString();
		}
	}
}
